<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气查询工具 - Weather Query Tool</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card h2 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .input-group {
            margin-bottom: 20px;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        
        .input-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        .input-group input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-bottom: 10px;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .city-list {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }
        
        .city-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        
        .city-item:hover {
            background-color: #e9ecef;
        }
        
        .city-item:last-child {
            border-bottom: none;
        }
        
        .city-name {
            font-weight: bold;
            color: #667eea;
        }
        
        .city-coords {
            color: #666;
            font-family: monospace;
        }
        
        .results {
            grid-column: 1 / -1;
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-top: 20px;
        }
        
        .weather-info {
            background: linear-gradient(135deg, #74b9ff, #0984e3);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .weather-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .weather-item {
            background: rgba(255,255,255,0.1);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .weather-icon {
            font-size: 2em;
            margin-bottom: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .error {
            background: #ff7675;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }
        
        .success {
            background: #00b894;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🌤️ 天气查询工具</h1>
            <p>Weather Query Tool - 支持全球天气查询</p>
        </div>
        
        <div class="main-content">
            <div class="card">
                <h2>📍 坐标输入</h2>
                <div class="input-group">
                    <label for="latitude">纬度 (Latitude)</label>
                    <input type="number" id="latitude" step="0.0001" placeholder="例如: 39.9042" />
                </div>
                <div class="input-group">
                    <label for="longitude">经度 (Longitude)</label>
                    <input type="number" id="longitude" step="0.0001" placeholder="例如: 116.4074" />
                </div>
                <button class="btn" onclick="queryCurrentWeather()">🌤️ 查询当前天气</button>
                <button class="btn" onclick="queryForecast()">📅 查询3天预报</button>
                
                <div class="city-list">
                    <h3>🏙️ 常用城市坐标</h3>
                    <div class="city-item" onclick="fillCoordinates(39.9042, 116.4074)">
                        <span class="city-name">北京</span>
                        <span class="city-coords">39.9042, 116.4074</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(31.2304, 121.4737)">
                        <span class="city-name">上海</span>
                        <span class="city-coords">31.2304, 121.4737</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(23.1291, 113.2644)">
                        <span class="city-name">广州</span>
                        <span class="city-coords">23.1291, 113.2644</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(22.3193, 114.1694)">
                        <span class="city-name">深圳</span>
                        <span class="city-coords">22.3193, 114.1694</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(30.2741, 120.1551)">
                        <span class="city-name">杭州</span>
                        <span class="city-coords">30.2741, 120.1551</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(30.5728, 104.0668)">
                        <span class="city-name">成都</span>
                        <span class="city-coords">30.5728, 104.0668</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(40.7128, -74.0060)">
                        <span class="city-name">纽约</span>
                        <span class="city-coords">40.7128, -74.0060</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(51.5074, -0.1278)">
                        <span class="city-name">伦敦</span>
                        <span class="city-coords">51.5074, -0.1278</span>
                    </div>
                    <div class="city-item" onclick="fillCoordinates(35.6762, 139.6503)">
                        <span class="city-name">东京</span>
                        <span class="city-coords">35.6762, 139.6503</span>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h2>🏙️ 批量查询</h2>
                <div class="input-group">
                    <label for="batchInput">城市坐标列表</label>
                    <textarea id="batchInput" rows="8" placeholder="格式: 城市名称,纬度,经度&#10;示例:&#10;北京,39.9042,116.4074&#10;上海,31.2304,121.4737&#10;广州,23.1291,113.2644" style="width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 14px; resize: vertical;"></textarea>
                </div>
                <button class="btn" onclick="batchQuery()">🚀 批量查询天气</button>
                <button class="btn" onclick="clearResults()" style="background: #e74c3c;">🗑️ 清空结果</button>
            </div>
        </div>
        
        <div id="results" class="results" style="display: none;">
            <h2>📊 查询结果</h2>
            <div id="weatherResults"></div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:5205';
        
        function showLoading() {
            document.getElementById('results').style.display = 'block';
            document.getElementById('weatherResults').innerHTML = '<div class="loading">⏳ 正在查询天气数据...</div>';
        }
        
        function showError(message) {
            document.getElementById('results').style.display = 'block';
            document.getElementById('weatherResults').innerHTML = '<div class="error">❌ ' + message + '</div>';
        }
        
        function showSuccess(message) {
            document.getElementById('results').style.display = 'block';
            document.getElementById('weatherResults').innerHTML = '<div class="success">✅ ' + message + '</div>';
        }
        
        function showWeatherResults(data) {
            document.getElementById('results').style.display = 'block';
            document.getElementById('weatherResults').innerHTML = data;
        }
        
        function getCoordinates() {
            const lat = parseFloat(document.getElementById('latitude').value);
            const lon = parseFloat(document.getElementById('longitude').value);
            
            if (isNaN(lat) || isNaN(lon)) {
                alert('请输入有效的坐标');
                return null;
            }
            
            if (lat < -90 || lat > 90) {
                alert('纬度必须在-90到90之间');
                return null;
            }
            
            if (lon < -180 || lon > 180) {
                alert('经度必须在-180到180之间');
                return null;
            }
            
            return { latitude: lat, longitude: lon };
        }
        
        // 测试不同的请求格式
        async function testDifferentFormats(coords) {
            const formats = [
                // 格式1: 标准MCP格式
                {
                    name: '标准MCP格式',
                    body: {
                        jsonrpc: '2.0',
                        id: Date.now().toString(),
                        method: 'tools/call',
                        params: {
                            name: 'get-current-weather',
                            arguments: coords
                        }
                    }
                },
                // 格式2: 简化格式
                {
                    name: '简化格式',
                    body: {
                        method: 'get-current-weather',
                        latitude: coords.latitude,
                        longitude: coords.longitude
                    }
                },
                // 格式3: 直接参数格式
                {
                    name: '直接参数格式',
                    body: {
                        latitude: coords.latitude,
                        longitude: coords.longitude
                    }
                }
            ];
            
            for (const format of formats) {
                try {
                    console.log(`🔄 尝试格式: ${format.name}`);
                    console.log('📤 请求数据:', JSON.stringify(format.body, null, 2));
                    
                    const response = await fetch(API_BASE, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json, text/event-stream, */*'
                        },
                        body: JSON.stringify(format.body),
                        mode: 'cors' // 明确启用CORS
                    });
                    
                    console.log(`📥 ${format.name} 响应:`, response.status, response.statusText);
                    
                    if (response.ok) {
                        const result = await response.text();
                        console.log(`✅ ${format.name} 成功:`, result);
                        return { success: true, format: format.name, data: result };
                    } else {
                        const errorText = await response.text();
                        console.log(`❌ ${format.name} 失败:`, response.status, errorText);
                    }
                } catch (error) {
                    console.log(`❌ ${format.name} 异常:`, error.message);
                }
                
                // 延迟避免请求过快
                await new Promise(resolve => setTimeout(resolve, 200));
            }
            
            return { success: false, error: '所有格式都失败了' };
        }
        
        async function queryCurrentWeather() {
            const coords = getCoordinates();
            if (!coords) return;
            
            showLoading();
            
            try {
                console.log('🌤️ 查询当前天气:', coords);
                console.log('📡 请求地址:', API_BASE);
                
                // 首先尝试健康检查
                try {
                    const healthResponse = await fetch(API_BASE + '/health', {
                        method: 'GET',
                        mode: 'cors'
                    });
                    console.log('🏥 健康检查:', healthResponse.status, healthResponse.statusText);
                } catch (healthError) {
                    console.log('🏥 健康检查失败:', healthError.message);
                }
                
                // 尝试不同的请求格式
                const result = await testDifferentFormats(coords);
                
                if (result.success) {
                    const weatherData = parseWeatherResponse(result.data);
                    showWeatherResults(formatCurrentWeather(weatherData));
                } else {
                    // 如果所有格式都失败，尝试简单的GET请求
                    console.log('🔄 尝试简单GET请求...');
                    try {
                        const simpleResponse = await fetch(`${API_BASE}?lat=${coords.latitude}&lon=${coords.longitude}`, {
                            method: 'GET',
                            mode: 'cors'
                        });
                        
                        if (simpleResponse.ok) {
                            const simpleResult = await simpleResponse.text();
                            showWeatherResults(formatCurrentWeather({ result: simpleResult }));
                        } else {
                            throw new Error(`所有请求方式都失败了。最后尝试状态: ${simpleResponse.status}`);
                        }
                    } catch (simpleError) {
                        throw new Error(`所有请求方式都失败了: ${simpleError.message}`);
                    }
                }
                
            } catch (error) {
                console.error('❌ 查询失败:', error);
                showError('查询失败: ' + error.message);
            }
        }
        
        async function queryForecast() {
            const coords = getCoordinates();
            if (!coords) return;
            
            showLoading();
            
            try {
                console.log('📅 查询天气预报:', coords);
                
                const requestBody = {
                    jsonrpc: '2.0',
                    id: Date.now().toString(),
                    method: 'tools/call',
                    params: {
                        name: 'get-forecast',
                        arguments: coords
                    }
                };
                
                const response = await fetch(API_BASE, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json, text/event-stream, */*'
                    },
                    body: JSON.stringify(requestBody),
                    mode: 'cors'
                });
                
                console.log('📥 响应状态:', response.status, response.statusText);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('❌ HTTP错误:', errorText);
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.text();
                console.log('📥 响应内容:', result);
                
                const weatherData = parseWeatherResponse(result);
                showWeatherResults(formatForecast(weatherData));
                
            } catch (error) {
                console.error('❌ 查询失败:', error);
                showError('查询失败: ' + error.message);
            }
        }
        
        async function batchQuery() {
            const input = document.getElementById('batchInput').value.trim();
            if (!input) {
                alert('请输入城市坐标');
                return;
            }
            
            const cities = input.split('\n').filter(line => line.trim());
            if (cities.length === 0) {
                alert('请输入有效的城市坐标');
                return;
            }
            
            showLoading();
            let allResults = '';
            
            for (const cityLine of cities) {
                const parts = cityLine.split(',');
                if (parts.length !== 3) {
                    allResults += '<div class="error">❌ 格式错误: ' + cityLine + '</div>';
                    continue;
                }
                
                const [name, lat, lon] = parts;
                const latNum = parseFloat(lat);
                const lonNum = parseFloat(lon);
                
                if (isNaN(latNum) || isNaN(lonNum)) {
                    allResults += '<div class="error">❌ 坐标无效: ' + cityLine + '</div>';
                    continue;
                }
                
                try {
                    const requestBody = {
                        jsonrpc: '2.0',
                        id: Date.now().toString(),
                        method: 'tools/call',
                        params: {
                            name: 'get-current-weather',
                            arguments: { latitude: latNum, longitude: lonNum }
                        }
                    };
                    
                    const response = await fetch(API_BASE, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json, text/event-stream, */*'
                        },
                        body: JSON.stringify(requestBody),
                        mode: 'cors'
                    });
                    
                    if (response.ok) {
                        const result = await response.text();
                        const weatherData = parseWeatherResponse(result);
                        allResults += formatCityWeather(name, weatherData);
                    } else {
                        const errorText = await response.text();
                        allResults += '<div class="error">❌ ' + name + ': HTTP ' + response.status + ' - ' + errorText + '</div>';
                    }
                    
                    // 延迟避免请求过快
                    await new Promise(resolve => setTimeout(resolve, 500));
                    
                } catch (error) {
                    allResults += '<div class="error">❌ ' + name + ': ' + error.message + '</div>';
                }
            }
            
            showWeatherResults(allResults);
        }
        
        function parseWeatherResponse(response) {
            try {
                console.log('🔍 解析响应:', response);
                
                if (response.startsWith('event: message')) {
                    const dataStart = response.indexOf('data: ');
                    if (dataStart !== -1) {
                        const dataContent = response.substring(dataStart + 6).trim();
                        console.log('📊 SSE数据内容:', dataContent);
                        return JSON.parse(dataContent);
                    }
                }
                
                // 尝试直接解析JSON
                const parsed = JSON.parse(response);
                console.log('📊 解析后的数据:', parsed);
                return parsed;
                
            } catch (error) {
                console.error('❌ 解析响应失败:', error);
                return { error: '解析响应失败: ' + error.message };
            }
        }
        
        function formatCurrentWeather(data) {
            if (data.error) {
                return '<div class="error">❌ 服务端错误: ' + data.error + '</div>';
            }
            
            try {
                const result = data.result?.content?.[0]?.text || data.result?.content || data.result || data;
                return '<div class="weather-info">' +
                    '<h3>🌤️ 当前天气信息</h3>' +
                    '<div style="white-space: pre-line; font-family: monospace;">' + result + '</div>' +
                    '</div>';
            } catch (error) {
                return '<div class="error">❌ 格式化失败: ' + error.message + '</div>';
            }
        }
        
        function formatForecast(data) {
            if (data.error) {
                return '<div class="error">❌ 服务端错误: ' + data.error + '</div>';
            }
            
            try {
                const result = data.result?.content?.[0]?.text || data.result?.content || data.result || data;
                return '<div class="weather-info">' +
                    '<h3>📅 3天天气预报</h3>' +
                    '<div style="white-space: pre-line; font-family: monospace;">' + result + '</div>' +
                    '</div>';
            } catch (error) {
                return '<div class="error">❌ 格式化失败: ' + error.message + '</div>';
            }
        }
        
        function formatCityWeather(cityName, data) {
            if (data.error) {
                return '<div class="error">❌ ' + cityName + ': ' + data.error + '</div>';
            }
            
            try {
                const result = data.result?.content?.[0]?.text || data.result?.content || data.result || data;
                return '<div class="weather-info">' +
                    '<h3>📍 ' + cityName + ' 天气</h3>' +
                    '<div style="white-space: pre-line; font-family: monospace;">' + result + '</div>' +
                    '</div>';
            } catch (error) {
                return '<div class="error">❌ ' + cityName + ': 格式化失败</div>';
            }
        }
        
        function clearResults() {
            document.getElementById('results').style.display = 'none';
            document.getElementById('weatherResults').innerHTML = '';
        }
        
        function fillCoordinates(lat, lon) {
            document.getElementById('latitude').value = lat;
            document.getElementById('longitude').value = lon;
        }
        
        // 测试连接功能
        async function testConnection() {
            try {
                console.log('🔍 测试服务端连接...');
                
                // 尝试多种连接方式
                const testUrls = [
                    API_BASE + '/health',
                    API_BASE + '/',
                    API_BASE
                ];
                
                for (const url of testUrls) {
                    try {
                        console.log(`🔍 测试URL: ${url}`);
                        const response = await fetch(url, {
                            method: 'GET',
                            mode: 'cors',
                            headers: {
                                'Accept': 'application/json, */*'
                            }
                        });
                        
                        console.log(`📥 ${url} 响应:`, response.status, response.statusText);
                        
                        if (response.ok) {
                            showSuccess(`✅ 服务端连接正常 (${url})`);
                            return;
                        }
                    } catch (urlError) {
                        console.log(`❌ ${url} 失败:`, urlError.message);
                    }
                }
                
                showError('❌ 所有连接测试都失败了');
                
            } catch (error) {
                console.error('❌ 连接测试失败:', error);
                showError('❌ 无法连接到服务端: ' + error.message);
            }
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('🌤️ 天气查询工具已加载');
            console.log('📡 连接到服务端: ' + API_BASE);
            
            // 自动测试连接
            setTimeout(testConnection, 1000);
        });
    </script>
</body>
</html>
